package com.junchenrobot.mes.handler;

import com.junchenrobot.mes.annotation.RcsResponseBody;
import com.junchenrobot.mes.response.BaseResponse;
import com.junchenrobot.mes.response.impl.MesResponse;
import com.junchenrobot.mes.response.impl.RcsResponse;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Objects;

/**
 * 响应消息处理程序 统一封装消息返回
 *
 * @author SeaWave
 * @date 2022/10/19
 */
@RestControllerAdvice("com.junchenrobot.mes.controller")
public class ResponseMessageHandler implements ResponseBodyAdvice<Object> {
    
    
    /**
     * 是否开启统一封装
     *
     * @param returnType    返回类型
     * @param converterType 转换器类型
     * @return boolean
     */
    @Override
    public boolean supports(MethodParameter returnType,
                            Class<? extends HttpMessageConverter<?>> converterType) {
        return !BaseResponse.class.isAssignableFrom(returnType.getParameterType());
    }
    
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType,
                                  MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        
        boolean annotationPresent = Objects.requireNonNull(returnType.getMethod())
                                           .isAnnotationPresent(RcsResponseBody.class);
        if (annotationPresent) {
            return new RcsResponse().success(body);
        }
        return new MesResponse<>().success(body);
    }
    
}
